<template>
  <div>
    <Drawer v-model="patientDetail" width="960" @on-close="cancelDrawer">
      <div class="sky-detail" v-if="patientDetail">
        <PageHeader>
          <div slot="title" class="sky-title">
            <h3>
              <Tooltip
                placement="top"
                content="共享数据"
                v-if="+data.is_share === 1"
              >
                <Icon type="ios-share" />
              </Tooltip>

              {{ data.true_name || data.user_name }}
              <Poptip trigger="hover" placement="bottom" width="165">
                <span>
                  <Icon type="ios-albums-outline"></Icon>
                </span>
                <List header="历史号码" slot="content">
                  <template
                    v-if="data.history_mobile && data.history_mobile.length > 0"
                  >
                    <ListItem
                      v-for="(item, index) in data.history_mobile"
                      :key="index"
                      >{{ item }}</ListItem
                    >
                  </template>
                  <ListItem v-else>暂无数据</ListItem>
                </List>
              </Poptip>
              <span>{{ data.gender_str }}</span>
              <span>{{ data.age }}</span>
              <Tag v-if="data.patient_status_id_str === '失效'" color="blue">
                {{ data.patient_status_id_str }}
              </Tag>
              <Tag
                v-else-if="data.patient_status_id_str === '跟进中'"
                color="volcano"
                >{{ data.patient_status_id_str }}</Tag
              >
              <Tag
                v-else-if="data.patient_status_id_str === '预约'"
                color="cyan"
                >{{ data.patient_status_id_str }}</Tag
              >
              <Tag
                v-else-if="data.patient_status_id_str === '到诊'"
                color="green"
                >{{ data.patient_status_id_str }}</Tag
              >
              <Tag
                v-else-if="data.patient_status_id_str === '已到老患者'"
                color="orange"
                >{{ data.patient_status_id_str }}</Tag
              >
              <Tag v-else-if="data.patient_status_id_str" color="orange">
                {{ data.patient_status_id_str }}
              </Tag>
              <tag color="primary" v-if="data.clinic_id_str">
                {{ data.clinic_id_str }}
              </tag>
              <span class="foundTime">创建时间：{{ data.created_at_str }}</span>
              <span v-hasC="btnShow[0]">
                <b
                  v-if="+data.is_subscribe === 1"
                  class="ivu-ml-16"
                  @click="handleFollow(data.is_subscribe)"
                >
                  <Icon type="md-heart" color="red"></Icon>
                </b>
                <b
                  v-else
                  @click="handleFollow(data.is_subscribe)"
                  class="ivu-ml-16"
                >
                  <Icon type="md-heart-outline"></Icon>
                </b>
              </span>
            </h3>
          </div>
          <div slot="action">
            <ButtonGroup>
              <Button
                v-hasC="btnShow[6]"
                v-if="data.is_show_diseases_check"
                @click="checkDis"
                :disabled="data.is_show_diseases_check == 2"
                >{{
                  data.is_show_diseases_check == 2 ? "病种已核验" : "病种待核验"
                }}</Button
              >
              <Button v-hasC="btnShow[1]" @click="handleRender">备注</Button>
              <Button v-hasC="btnShow[2]" @click="handleOpenDrawer"
                >编辑</Button
              >
            </ButtonGroup>
            <Button
              v-hasC="btnShow[3]"
              type="primary"
              @click="handleReturnVisit"
              >回访</Button
            >
          </div>
          <div slot="content">
            <!--标签-->
            <tags
              ref="tags"
              v-if="tagsshow"
              :btnShow="btnShow"
              :data="data"
              :bools="bools"
              @askData="askData"
            ></tags>
            <DescriptionList :col="4">
              <Description
                v-if="data.mobile && data.mobile.length === 0"
                term="手机号:"
              >
              </Description>
              <Description
                v-else
                :term="
                  `手机号${
                    data.mobile && data.mobile.length === 1 ? '' : index + 1
                  }：`
                "
                v-for="(item, index) of data.mobile"
                :key="index"
              >
                {{ item }}
              </Description>
              <!-- <Row
                                type="flex"
                                justify="space-between"
                                align="middle"
                                style="margin: 0 16px 16px 16px;"
                            >
                                <Col
                                    span="6"
                                    v-for="(item, index) of data.mobile"
                                    :key="index"
                                >
                                    <span>
                                        手机号{{ index + 1 }}：{{ item }}
                                    </span>
                                </Col>
                            </Row> -->
              <Description term="微信号：">
                <span>{{ data.wechat_id }}</span>
                <Poptip
                  v-if="data.history_wechat && data.history_wechat.length > 0"
                  trigger="hover"
                  placement="bottom"
                  width="118"
                >
                  <Icon type="ios-albums-outline"></Icon>
                  <List header="历史微信号" slot="content">
                    <ListItem
                      v-for="(item, index) in data.history_wechat"
                      :key="index"
                      >{{ item }}
                    </ListItem>
                  </List>
                </Poptip>
              </Description>
              <Description term="病种：">
                {{
                  data.patient_diseases_child_id_str ||
                    data.patient_diseases_id_str
                }}
              </Description>
              <!-- <Description term="发病部位：">{{ data.str }}</Description> -->
              <Description term="发病部位：">
                <Ellipsis
                  v-if="data.str"
                  :text="data.str"
                  :length="8"
                  tooltip
                ></Ellipsis>
              </Description>
              <Description term="归属部门：">{{
                data.department_name
              }}</Description>
              <Description term="归属人：">{{
                +data.patient_data_type === 0 ? data.belong_member_name : ""
              }}</Description>
              <Description term="回访次数：">
                {{ data.callback_count }}
              </Description>
              <Description term="下次回访时间：">
                {{ splitfun(data.next_callback_time_str) }}
              </Description>
              <Description term="预到时间：">
                {{ splitfun(data.appointment_time_str) }}
              </Description>
              <Description term="到诊时间：">
                {{ splitfun(data.revisiting_time_str) }}
              </Description>
              <Description term="城市：">
                {{ data.city_name ? data.city_name : "" }}
              </Description>
            </DescriptionList>
            <DescriptionList :col="1">
              <Description term="详细地址：">{{ data.address }}</Description>
              <Description term="备注：">{{ data.remark }}</Description>
            </DescriptionList>
          </div>
        </PageHeader>
        <div class="sky-cont" :key="jobnumberKey">
          <Tabs
            v-model="name1"
            :animated="false"
            @on-click="changetabs(name1)"
            name="children"
          >
            <TabPane label="回访记录" name="name1" tab="children">
              <visitRecord
                :id="params.id"
                v-if="name1 === 'name1'"
                ref="visitRecord"
              ></visitRecord>
            </TabPane>
            <TabPane :label="`病历图(${totalImg})`" name="name5" tab="children">
              <casemessage
                :userId="this.params.id"
                :userInfo="data"
                :disList="disList"
                ref="casemessage"
                @patientfun="$emit('cancelDrawer')"
                :name1="name1"
                :listParams="listParams"
                @getTotal="getTotal"
                @patientfuns="askDataing()"
                @closeModal="cancelDrawer"
                @handleOpen="handleOpen"
              ></casemessage>
            </TabPane>
            <TabPane
              v-if="is_show_echat"
              label="沟通记录"
              name="name6"
              tab="children"
            >
              <chartList ref="chartList"></chartList>
            </TabPane>
            <TabPane label="营销信息" name="name2" tab="children">
              <origins ref="origins"></origins>
            </TabPane>
            <TabPane :label="label" name="name4" tab="children">
              <wechat ref="wechat" :userInfo="data"></wechat>
            </TabPane>
            <TabPane label="编辑日志" name="name3" tab="children">
              <Journal ref="Journal"></Journal>
            </TabPane>
          </Tabs>
        </div>
      </div>
      <Spin size="large" fix v-if="spinShow"></Spin>
    </Drawer>
    <edit-patient
      ref="editPatient"
      @patientfun="handleOpens(params.id)"
      @closeAll="closeAll"
    ></edit-patient>
    <return-visit
      :viewInfo="viewInfo"
      ref="returnVisit"
      @patientfuns="handleOpenss(params.id)"
    ></return-visit>
    <Modal v-model="remarks" :closable="false">
      <Input
        type="textarea"
        v-model="remark"
        :rows="3"
        placeholder="请输入备注内容"
      ></Input>
      <div slot="footer">
        <Button @click="remarks = false">取消</Button>
        <Button type="primary" :loading="remarksloading" @click="handleSubmit"
          >确定</Button
        >
      </div>
    </Modal>
    <Modal v-model="showDis" :closable="false" width="400">
      <Select v-model="patientDis" label="选择病种">
        <template v-for="item in disList">
          <OptionGroup v-if="item.children.length > 0" :label="item.label">
            <template v-for="ele in item.children">
              <Option v-if="ele.status == 1" :value="ele.value">{{
                ele.label
              }}</Option>
            </template>
          </OptionGroup>
          <template v-else>
            <Option v-if="item.status == 1" :value="item.value">{{
              item.label
            }}</Option>
          </template>
        </template>
      </Select>
      <div slot="footer">
        <Button @click="showDis = false">取消</Button>
        <Button type="primary" :loading="disloading" @click="handleDis"
          >确定</Button
        >
      </div>
    </Modal>
  </div>
</template>
<script>
import editPatient from "@/components/editPatient";
import returnVisit from "@/components/returnVisit";
import visitRecord from "./returnVisit";
import casemessage from "./casemessage";
import Journal from "./Journal";
import origins from "./origins";
import wechat from "./wechat";
import tags from "./tags";
import chartList from "./chartList";
import { worktodowechatinfo } from "@api/hqapi/indextwo";
import { patientindextabtotal } from "@/api/hqapi";
import { mapState, mapMutations, mapGetters } from "vuex";

import {
  patientindexinfo,
  patientindexeditremark,
  patientindexsub,
  patientindexedittags,
  patientindexpatienttags,
  patientCheckDiseases,
  diseaseList,
} from "@/api/hqapi";
import util from "@/libs/util";
export default {
  components: {
    visitRecord,
    Journal,
    origins,
    editPatient,
    returnVisit,
    casemessage,
    wechat,
    tags,
    chartList,
  },
  props: {
    btnShow: {
      type: Array,
      require: true,
    },
    viewInfo: {
      type: Object,
      default: () => {},
    },
    tabChange: {
      type: Boolean,
      default: false,
    },
    listParams: {
      type: Object,
      default: () => {},
    },
  },
  watch: {
    // patientDetail() {
    //   if (this.patientDetail) {
    //     patientindextabtotal({ type: 0 }).then((res) => {
    //       this.disList = res.condition.diseases;
    //     });
    //   }
    // },
    viewInfo: {
      handler(value) {},
      deep: true,
    },
  },
  computed: {
    isShowX() {
      let id = this.btnShow[5].name;
      let arr = JSON.parse(localStorage.getItem("menus")).action;
      let flag = arr.find((ee) => {
        return ee.marking === id;
      });
      return flag ? true : false;
    },
    ...mapState("power/export", ["wsIsConnect"]),
    ...mapState("admin/account", ["closeRefresh"]),
  },
  mounted() {
    this.name1 = "name1";
  },
  data() {
    return {
      totalImg: 0,
      disList: [],
      disloading: false,
      showDis: false,
      patientDis: "",
      jobnumberKey: +new Date(),
      is_show_echat: false,
      label: null,
      params: { id: "", is_share: "", source_type: "" },
      data: {},
      datas: {},
      patientDetail: false,
      remarksloading: false,
      follow: true,
      bool: false,
      remarks: false,
      bools: false,
      remark: "",
      // taglist: [],
      tagalllist: [],
      // taglists: [],
      isEdit: {},
      name1: "",
      content: 13358658658 + "<br/>" + 15958658658 + "<br/>" + 18932658858,
      value:
        "平时7点下班，也没有休息天，想过段时间再看，推了全免检查到31号，手机短信发地址， 一直说谢谢，希望比较小",
      labelList: [
        {
          value: "活动用户",
          label: "活动用户",
        },
        {
          value: "价格敏感",
          label: "价格敏感",
        },
      ],
      detailTabList: [
        {
          label: "回访记录",
          name: "returnVisit",
        },
        {
          label: "来源信息",
          name: "record",
        },
        {
          label: "编辑日志",
          name: "log",
        },
      ],
      Interval: null,
      tagsshow: true,
      spinShow: false,
    };
  },
  methods: {
    getTotal(num = 0) {
      this.totalImg = num;
    },
    ...mapMutations("power/export", ["changeWxAllData"]),
    closeAll() {
      // this.$emit("cancelDrawer");
      // this.patientDetail = false;
    },
    cancelDrawer(e) {
      this.patientDetail = false;
      // this.$emit("cancelDrawer")
      if (this.closeRefresh) {
        this.$emit("askData");
      }
      // this.okmodal()
      clearInterval(this.Interval);
    },
    askDatas() {
      this.askData();
      this.$emit("askData");
    },
    handleOpen(row, bool) {
      this.isEdit = row;
      this.bool = bool;
      this.name1 = "name1";
      this.tagalllist = [];
      // this.taglists = [];
      this.data = {};
      this.params.id = row.id;
      this.params.is_share = row.is_share;
      this.params.source_type = row.source_type;
      this.askData();
      if (this.tabChange) {
        this.name1 = "name5";
        diseaseList().then((res) => {
          this.disList = res.condition.diseases;
        });
        return;
      }
      this.$nextTick(() => {
        this.changetabs(this.name1);
      });
    },
    handleOpens(id) {
      let name = this.$parent.name;
      this.$emit("cancelDrawer");
      if (name && name === "view") {
        this.patientDetail = false;
      } else {
        this.name1 = "name1";
        this.tagalllist = [];
        // this.taglists = [];
        this.data = {};
        this.params.id = id;
        this.askData();
        this.changetabs(this.name1);
      }
    },
    handleOpenss(id) {
      let name = this.$parent.name;
      this.$emit("cancelDrawer");
      if (name && name === "view") {
        this.patientDetail = false;
      } else {
        this.name1 = "name1";
        this.tagalllist = [];
        // this.taglists = [];
        this.data = {};
        this.params.id = id;
        this.askData();
        this.changetabs(this.name1);
      }
      this.askDatatag();
    },
    askDatatag() {
      this.askDatatags();
      let num = 0;
      clearInterval(this.Interval);
      this.Interval = setInterval(() => {
        if (num >= 6) clearInterval(this.Interval);
        num++;
        this.askDatatags();
      }, 5000);
    },
    askDatatags() {
      // patientindexpatienttags({id:this.params.id}).then(res=>{
      //     this.taglist = [];
      //     for (let item of res.tags) {
      //         for (let it of item.tags_arr) {
      //             this.taglist.push(`${it.tag_id}-${item.wechatid}`);
      //         }
      //     }
      //     this.taglists = JSON.parse(JSON.stringify(this.taglist));
      //     this.data.tags = res.tags
      // })
    },
    changetabs(name) {
      if (name === "name1") {
        this.$nextTick(() => {
          this.$refs.visitRecord.askData(this.params.id);
        });
      } else if (name === "name2") this.$refs.origins.askData(this.params.id);
      else if (name === "name4") this.$refs.wechat.askData(this.params.id);
      else if (name === "name3") this.$refs.Journal.askData(this.params.id);
      else if (name === "name6") this.$refs.chartList.askData(this.params.id);
      else if (name === "name5") {
        this.$nextTick(() => {
          this.$refs.casemessage.askDatas(this.params.id);
        });
      }
    },
    askDataing() {
      this.patientDetail = true;
      this.spinShow = true;
      patientindexinfo(this.params).then((res) => {
        this.is_show_echat = res.is_show_echat;
        // this.taglist = [];
        // for (let item of res.tags) {
        //     for (let it of item.tags_arr) {
        //         this.taglist.push(it.tag_id);
        //     }
        // }
        if (res.body_parts_ids_str.length > 0) {
          res.str = res.body_parts_ids_str.join(",");
        } else {
          res.str = "";
        }
        let UnionId = util.cookies.get("uuid") ? util.cookies.get("uuid") : 0;
        this.bools = res.belong_member_id == UnionId;
        if (+res.is_bind_wechat === 1) {
          this.label = (h) => {
            return h("div", [
              h("Icon", {
                props: {
                  custom: "i-icon icon-weixin",
                  size: 20,
                },
              }),
              h("span", "微信信息"),
            ]);
          };
        } else {
          this.label = (h) => {
            return h("div", [h("span", "微信信息")]);
          };
        }
        // this.taglists = JSON.parse(JSON.stringify(this.taglist));
        this.data = res;
        this.$nextTick(() => {
          this.spinShow = false;
        });
      });
    },
    askData() {
      this.tagsshow = false;
      this.patientDetail = true;
      this.spinShow = true;
      patientindexinfo(this.params).then((res) => {
        this.is_show_echat = res.is_show_echat;
        // this.jobnumberKey = +new Date();
        // this.taglist = [];
        // for (let item of res.tags) {
        //     for (let it of item.tags_arr) {
        //         this.taglist.push(`${it.tag_id}-${item.wechatid}`);
        //     }
        // }
        if (res.body_parts_ids_str.length > 0) {
          res.str = res.body_parts_ids_str.join(",");
        } else {
          res.str = "";
        }
        let UnionId = util.cookies.get("uuid") ? util.cookies.get("uuid") : 0;
        this.bools = res.belong_member_id == UnionId;
        if (+res.is_bind_wechat === 1) {
          this.label = (h) => {
            return h("div", [
              h("Icon", {
                props: {
                  custom: "i-icon icon-weixin",
                  size: 20,
                },
              }),
              h("span", "微信信息"),
            ]);
          };
        } else {
          this.label = (h) => {
            return h("div", [h("span", "微信信息")]);
          };
        }

        // this.taglists = JSON.parse(JSON.stringify(this.taglist));
        this.data = res;
        this.totalImg = res.medical_image_num;
        this.patientDis = res.patient_diseases_child_id
          ? res.patient_diseases_child_id
          : res.patient_diseases_id;
        this.datas = JSON.parse(JSON.stringify(res));

        this.tagsshow = true;
        this.$nextTick(() => {
          this.spinShow = false;
        });
      });
    },
    splitfun(data) {
      if (data) {
        return data.split(" ")[0];
      }
    },
    handleReturnVisit() {
      this.$refs.returnVisit.handleReturnVisit(this.params.id, this.isEdit);
    },
    handleOpenDrawer() {
      if (this.bool) this.$refs.editPatient.handleEdit(this.params, true);
      else this.$refs.editPatient.handleEdit(this.params);
    },
    checkDis() {
      this.showDis = true;
      diseaseList().then((res) => {
        this.disList = res.condition.diseases;
      });
    },
    handleRender() {
      this.remarks = true;
      this.remark = "";
    },
    handleDis() {
      this.disloading = true;
      let params = {
        patient_user_id: this.params.id,
        patient_diseases_id: "",
        patient_diseases_child_id: "",
      };
      this.disList.forEach((ele) => {
        if (ele.value == this.patientDis) {
          params.patient_diseases_id = this.patientDis;
        } else {
          ele.children.forEach((child) => {
            if (child.value == this.patientDis) {
              params.patient_diseases_id = ele.value;
              params.patient_diseases_child_id = this.patientDis;
            }
          });
        }
      });
      patientCheckDiseases(params)
        .then((res) => {
          this.$Message.success("病种核验成功");
          // 判断关闭弹窗是否刷新
          this.$store.commit("admin/account/changeCloseRefresh", true);
          this.showDis = false;
          this.askData();
          this.disloading = false;
        })
        .catch(() => {
          this.disloading = false;
        });
    },
    handleSubmit() {
      this.remarksloading = true;
      patientindexeditremark({
        id: this.params.id,
        remark: this.remark,
      })
        .then((res) => {
          this.$Message.success("添加备注成功成功");
          this.remarks = false;
          this.remarksloading = false;
          // 判断关闭弹窗是否刷新
          this.$store.commit("admin/account/changeCloseRefresh", true);
          this.handleOpen(this.params);
          // this.$emit("cancelDrawer");
          // this.askData();
          // this.okmodal()
        })
        .catch(() => {
          this.remarksloading = false;
        });
    },
    // okmodal() {
    //     if (JSON.stringify(this.data) !== JSON.stringify(this.datas)) {
    //         let _tags_arr = []
    //         for (let item of this.tagalllist) {
    //             _tags_arr.push({id: this.params.id,wechatid:item.wechatid,old_tags_id:[],tags_ids:[]})
    //         }
    //         for (let item of  _tags_arr) {
    //             for (let it of this.datas.tags) {
    //                 if (item.wechatid == it.wechatid) {
    //                     for (let its of it.tags_arr) {
    //                         item.old_tags_id.push(its.tag_id)
    //                     }
    //                 }
    //             }
    //             for (let it of this.data.tags) {
    //                 if (item.wechatid == it.wechatid) {
    //                     for (let its of it.tags_arr) {
    //                         item.tags_ids.push(its.tag_id)
    //                     }
    //                 }
    //             }
    //         }
    //         for (let item of _tags_arr) {
    //             if (item.tags_ids.length>0&&item.old_tags_id.length>0) {
    //                 let config = {
    //                     id: item.id,
    //                     tags_ids:item.tags_ids.join(','),
    //                     wechatid:item.wechatid,
    //                     old_tags_id:item.old_tags_id.join(','),
    //                 };
    //                 patientindexedittags(config).then((res) => {
    //                 });
    //             }
    //         }
    //     }
    // },
    handleFollow(data) {
      let datas = +data === 1 ? 0 : 1;
      patientindexsub({ id: this.params.id, sub_type: datas }).then((res) => {
        this.askData();
        if (datas === 1) this.$Message.success("关注成功");
        else this.$Message.success("取关成功");
      });
    },
  },
  beforeDestroy() {},
};
</script>
<style scoped>
.sky-title {
  font-size: 16px;
  color: #333;
}

.sky-title span {
  font-size: 14px;
  font-weight: normal;
  margin: 0 8px;
}

.sky-cont {
  padding-left: 16px;
}

.sky-title .foundTime {
  color: #888;
  font-size: 12px;
}
</style>
<style>
.sky-detail .ivu-page-header {
  padding: 0 16px;
  border-bottom: none;
}

.sky-detail .ivu-tabs-bar {
  margin-bottom: 0px;
}
</style>
